package com.file.system.controller.system;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.system.WebUser;
import com.file.system.plugin.websocket.WebSocketServer;
import com.file.system.tools.regular.RegularUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.web.subject.support.DefaultWebSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.file.system.entity.res.BaseCode.Common.USER_OUT;

/**
 * shiro管理
 *
 * @author 靳春晖
 */
@RestController
@RequestMapping("/shiro")
public class ShiroController {

    @Autowired
    private SessionDAO sessionDAO;


    /**
     * 查询当前在线用户
     *
     * @return com.file.system.entity.res.CommonResult<java.util.List < com.file.system.entity.WebUser>>
     * @author 靳春晖
     */
    @PostMapping("/get/all")
    public CommonResult<List<WebUser>> selectAll() {
        List<WebUser> users = new ArrayList<>();

        //获取当前会话
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            //获取会话属性
            Object principal = session.getAttribute(DefaultWebSubjectContext.PRINCIPALS_SESSION_KEY);
            if (ObjectUtil.isNull(principal)) {
                continue;
            }

            SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principal;
            WebUser user = (WebUser) principalCollection.getPrimaryPrincipal();
            //获取IP地址
            user.setIp(session.getHost());
            //获取最后访问时间
            user.setLastAccessTime(DateUtil.format(session.getLastAccessTime(), "yyyy-MM-dd HH:mm"));
            users.add(user);
        }
        return CommonResult.ok().setResult(users);
    }


    /**
     * 踢出登录用户
     *
     * @param id 用户id
     * @return com.file.system.entity.res.CommonResult
     * @author 靳春晖
     */
    @PostMapping("/out/{id}")
    public CommonResult out(@PathVariable
                            @Validated
                            @NotNull(message = "用户id不能为空")
                            @Pattern(regexp = RegularUtil.ID, message = "用户id格式错误")
                            Long id) {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            //获取session中的principal
            Object principal = session.getAttribute(DefaultWebSubjectContext.PRINCIPALS_SESSION_KEY);
            //如果principal为空，则跳过
            if (ObjectUtil.isNull(principal)) {
                continue;
            }

            //将principal转换为SimplePrincipalCollection
            SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principal;
            //获取primaryPrincipal
            WebUser user = (WebUser) principalCollection.getPrimaryPrincipal();
            //如果id和user.getId()相等，则踢出用户
            if (ObjectUtil.equal(user.getId(), id)) {
                WebSocketServer.sendMessage(USER_OUT, USER_OUT.getMessage(), session.getId().toString());
                sessionDAO.delete(session);
                return CommonResult.ok().setText("踢出用户" + user.getUsername() + "成功");
            }
        }
        return CommonResult.fail().setText("踢出用户失败");
    }

}
